package com.secneo.appshare.adapter;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.secneo.appshare.R;
import com.secneo.appshare.api.RemoteApi.Comment;

public class CommentListAdapter extends BaseAdapter {
	
	private Context mContext ;
	private ArrayList<Comment> mList ;
	private Handler mHandler ;
	
	public CommentListAdapter(Context ctx, ArrayList<Comment> list, 
			Handler handler) {
		this.mContext = ctx;
		this.mList = list;
		this.mHandler = handler ;
	}
	
	public void freeDrawable()
	{
		for(int i=0; i<mList.size(); i++){
			if(mList.get(i).user_icon.contains("buildin") || 
					mList.get(i).user_icon_drawable == null)	
				continue ;
			BitmapDrawable a = (BitmapDrawable) mList.get(i).user_icon_drawable;
			if(a!=null && !a.getBitmap().isRecycled())
				a.getBitmap().recycle();
		}
		System.gc();
	}
	
	public void setList(ArrayList<Comment> list){
		mList = list ;
	}
	
	@Override
	public int getCount() {
		return mList.size();
	}

	@Override
	public Object getItem(int position) {
		return mList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		CommentItem commentItem = null ;
		final Comment comment = mList.get(position);
		if(convertView == null){
			View v = LayoutInflater.from(mContext).inflate(
					R.layout.appshare_activity_item, null);
			commentItem = new CommentItem();
			commentItem.mDataBackground = (LinearLayout) v
					.findViewById(R.id.data_background);
			commentItem.mUserIcon = (ImageView) v
					.findViewById(R.id.activity_user_icon);
			commentItem.mUserName = (TextView) v
					.findViewById(R.id.activity_user_name);
			commentItem.mData = (TextView) v
					.findViewById(R.id.activity_details);
			commentItem.mDate = (TextView) v
					.findViewById(R.id.activity_date);
			v.setTag(commentItem);
			convertView = v;
		} else {
			commentItem = (CommentItem) convertView.getTag();
		}
		
		commentItem.mUserIcon.setBackgroundDrawable(comment.user_icon_drawable) ;
		commentItem.mUserName.setText(comment.uname) ;
		commentItem.mData.setText(comment.comment) ;
		commentItem.mDate.setText(comment.date) ;
		
		return convertView;
	}
	
	class CommentItem {
		LinearLayout mDataBackground;
		ImageView mUserIcon;
		TextView mUserName;
		TextView mData;
		TextView mDate;
	}
}
